/*
 * Copyright (C) Antonio Ramon Morcillo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package soft.xitxarello.su.activities;

import org.holoeverywhere.app.Activity;
import org.holoeverywhere.widget.Toast;

import com.actionbarsherlock.view.MenuItem;
import com.bugsense.trace.BugSenseHandler;

import soft.xitxarello.su.R;
import soft.xitxarello.su.fragments.DetailFragment;
import soft.xitxarello.su.fragments.EmptyDetailFragment;

import android.content.Intent;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NavUtils;

/**
 * A base activity that handles common functionality in the application.
 * 
 * @see org.holoeverywhere.app.Activity
 */
public class BaseActivity extends Activity {

    // flag to recognize smartphone and less than 10 inches tablets
    protected boolean isSmartPhone = false;

    // flag to recognize tablets
    protected boolean isTablet = false;

    /**
     * Overrides a superclass method. Called when the activity is starting.
     * 
     * @param savedInstanceState A mapping from String values to various
     *            Parcelable types.
     * @see android.support.v4.app._HoloActivity#onCreate(Bundle
     *      savedInstanceState)
     * @see android.os.Bundle
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // Apply application ui style.
        setTheme(R.style.Light);

        // Parent method.
        super.onCreate(savedInstanceState);

        // Bugsense
        BugSenseHandler.initAndStartSession(this, "664ff953");

        // Ask for smartPhone device.
        if (getResources().getBoolean(R.bool.isSmartPhone)) {
            isSmartPhone = true;
        }

        // Ask for tablet device.
        if (getResources().getBoolean(R.bool.isTablet)) {
            isTablet = true;
        }

        // Set action bar background.
        // Drawable Resource:
        // /res/drawable/actionbar_background_pattern_tile.png
        BitmapDrawable bg = (BitmapDrawable) getResources().getDrawable(
                R.drawable.actionbar_background_pattern_tile);
        bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
        getSupportActionBar().setBackgroundDrawable(bg);

        // Enable the "home" button in the corner of the action bar.
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    /**
     * Overrides a superclass method. This hook is called whenever an item in
     * your options menu is selected.
     * 
     * @param item The menu item that was selected.
     * @see com.actionbarsherlock.view.MenuItem
     * @see org.holoeverywhere.app.Activity#onOptionsItemSelected(MenuItem item)
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case android.R.id.home:
                // "home" button disabled for the MainActivity.
                if (this instanceof MainActivity) {
                    return false;
                }
                // "home" button navigation enabled for the non MainActivity.
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * Overrides a superclass method. Receive the result from a previous call to
     * <code>startActivityForResult(Intent, int)</code>.
     * 
     * @param requestCode The integer request code originally supplied to
     *            startActivityForResult(), allowing you to identify who this
     *            result came from.
     * @param resultCode The integer result code returned by the child activity
     *            through its setResult().
     * @param intent An Intent, which can return result data to the caller
     *            (various data can be attached to Intent "extras").
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        // On Pre HONEYCOMB builds resultCode fails on Compatibility library
        // when launch activity from a fragment.
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            onActivityResultPreHoneycomb(requestCode, resultCode, intent);
        } else
            onActivityResultPostHoneycomb(requestCode, resultCode, intent);

    }

    /**
     * Receive the result from a previous method
     * <code> onActivityResult(int requestCode, int resultCode, Intent intent) </code>
     * when android version is less than HoneyComb.
     * 
     * @param requestCode The integer request code originally supplied to
     *            startActivityForResult(), allowing you to identify who this
     *            result came from.
     * @param resultCode The integer result code returned by the child activity
     *            through its setResult().
     * @param intent An Intent, which can return result data to the caller
     *            (various data can be attached to Intent "extras").
     */
    private void onActivityResultPreHoneycomb(int requestCode, int resultCode, Intent intent) {

        // Finish Activity on smartPhone.
        if (this instanceof DetailActivity) {
            finish();
        }
    }

    /**
     * Receive the result from a previous method
     * <code> onActivityResult(int requestCode, int resultCode, Intent intent) </code>
     * when android version is Ice Cream Sandwich or greater.
     * 
     * @param requestCode The integer request code originally supplied to
     *            startActivityForResult(), allowing you to identify who this
     *            result came from.
     * @param resultCode The integer result code returned by the child activity
     *            through its setResult().
     * @param intent An Intent, which can return result data to the caller
     *            (various data can be attached to Intent "extras").
     */
    private void onActivityResultPostHoneycomb(int requestCode, int resultCode, Intent intent) {

        // Show user what's on with TOAST.
        if (requestCode == DetailFragment.REQUEST_UNINSTALL) {

            // Application has been uninstalled.
            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(this, R.string.uninstall_ok,
                        Toast.LENGTH_SHORT).show();

                // Remove detail fragment on tablets.
                if (isTablet) {

                    // Get the fragment manager and transaction.
                    FragmentManager fm = getSupportFragmentManager();
                    FragmentTransaction ft = fm.beginTransaction();

                    // Replace detail FrameLayout with the unselected
                    // application
                    // fragment.
                    EmptyDetailFragment empty = new EmptyDetailFragment();
                    ft.replace(R.id.main_activity_detail, empty);

                    // Commit changes.
                    ft.commit();
                }

                // Finish Activity on smartPhone.
                if (this instanceof DetailActivity) {
                    finish();
                }

                // Uninstall intent has been canceled by user.
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(this,
                        R.string.uninstall_cancel, Toast.LENGTH_SHORT).show();

                // Uninstall intent fails.
            } else {
                Toast.makeText(this, R.string.uninstall_ko,
                        Toast.LENGTH_SHORT).show();
            }
        }
    }
}
